<template>
  <div class="role-page">
    <div class="btns-fun-field">
      <!-- v-if="rolePermission.addRolePerm" -->
      <el-button type="primary" @click.prevent="showAddEditDialog" :icon="Plus">
        新增角色
      </el-button>
    </div>
    <div class="table-field">
      <el-table
        :data="tableData"
        border
        stripe
        style="width: 100%"
        v-loading="tableLoading"
      >
        <el-table-column prop="name" label="角色名" width="200" />
        <el-table-column prop="createTime" label="创建时间" width="240" />
        <el-table-column prop="updateTime" label="更新时间" width="240" />
        <el-table-column label="操作" min-width="220px" fixed="right">
          <template #default="scope">
            <!-- v-if="rolePermission.editRolePerm" -->
            <el-button
              type="success"
              size="small"
              @click.prevent="showAddEditDialog(scope.row, 2)"
              >编辑</el-button
            >
            <!-- v-if="rolePermission.removeRolePerm" -->
            <el-button
              type="danger"
              size="small"
              @click.prevent="showRemoveDialog(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-field">
      <el-pagination
        v-model:current-page="formData.pageIndex"
        v-model:page-size="formData.pageSize"
        :page-sizes="[10, 20, 30, 40]"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="formData.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增、修改弹框 -->
    <RoleAddUpdate v-model="roleAddUpdateRef"></RoleAddUpdate>
    <!-- 删除模块 -->
    <RoleRemove v-model="roleRemoveRef"></RoleRemove>
  </div>
</template>
<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { getRolePagination, getPermissionTree } from '@/api/ums-user.api'
import RoleRemove from './component/RoleRemove.vue'
import RoleAddUpdate from './component/RoleAddUpdate.vue'

import { Plus } from '@element-plus/icons-vue'
import { useRolePermission } from '@/utils/permission.utils'
const rolePermission = useRolePermission()
const formData = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0,
})

let roleAddUpdateRef = reactive({
  visible: false,
  title: '角色',
  curSelectRow: {},
  permissionList: [],
  allPermissionSelected: false,
  form: {
    id: null,
    name: '',
    disabled: false,
    permissionIdList: [],
  },
  rules: {
    name: [
      { required: true, message: '请输入角色名', trigger: 'blur' },
      { min: 1, max: 30, message: '长度为1~30位', trigger: 'blur' },
    ],
  },
  refreshDataList: () => {
    getDataList()
  },
})
let roleRemoveRef = reactive({
  visible: false,
  title: '角色',
  curSelectRow: {},
  refreshDataList: () => {
    getDataList()
  },
})

const showAddEditDialog = (item: any, type: number) => {
  //新增角色
  if (item.target) {
    let form = {
      id: null,
      name: '',
      remark: '',
      disabled: false,
      permissionIdList: [],
    }
    roleAddUpdateRef.visible = true
    roleAddUpdateRef.form = form
    initPermissionCheck([])
    return
  }

  let form = {
    id: item.id,
    name: item.name,
    remark: item.remark,
    disabled: true,
    permissionIdList: item.permissionIdList,
  }
  roleAddUpdateRef.visible = true
  roleAddUpdateRef.form = form
  let permissionIdList = item.permissionIdList || []
  initPermissionCheck(permissionIdList)
}

const initPermissionCheck = (permissionIdList: any) => {
  let permissionValueList = permissionList.value || []
  console.log('permissionValueList...', permissionValueList)
  for (let permissionItem of permissionValueList) {
    let filterList = permissionIdList.filter((rowId: string) => {
      return `${permissionItem.id}` == rowId
    })
    permissionItem.selected = filterList.length > 0
    let children = permissionItem.children || []
    if (children) {
      for (let childItem of children) {
        let filterList = permissionIdList.filter((rowId: string) => {
          return `${childItem.id}` == rowId
        })
        childItem.selected = filterList.length > 0
      }
    }
  }
  isAllSelected()
}

const tableLoading = ref(false)
const tableData = ref([])
const showRemoveDialog = (item: any) => {
  //显示删除框。
  roleRemoveRef.visible = true
  //收集数据。
  roleRemoveRef.curSelectRow = item
}

const handleSizeChange = (value: number) => {
  console.log('handleSizeChange...', value)
  formData.pageSize = value
  getDataList()
}

const handleCurrentChange = (value: number) => {
  console.log('handleCurrentChange...', value)
  formData.pageIndex = value
  getDataList()
}

const getDataList = () => {
  tableLoading.value = true
  getRolePagination({
    pageSize: formData.pageSize,
    pageIndex: formData.pageIndex,
  })
    .then(function (res: any) {
      tableLoading.value = false
      tableData.value = res.list || []
      formData.total = Number(res.total)
    })
    .catch((error) => {
      console.log(error)
      tableLoading.value = false
    })
}

const permissionList = ref([])
const startGetPermissionTree = () => {
  getPermissionTree({}).then(function (res: any) {
    res = res.map((item: any) => {
      item.selected = false
      if (item.children && item.children.length > 0) {
        for (let i = 0; i < item.children.length; i++) {
          let row = item.children[i]
          row.selected = false
        }
      }
      return item
    })
    //得到整颗权限树
    permissionList.value = res
    roleAddUpdateRef.permissionList = res
  })
}

const isAllSelected = () => {
  let permissionValueList = permissionList.value || []
  console.log('permissionValueList: ', permissionValueList)
  for (let item of permissionValueList) {
    if (!(item as any).selected) {
      roleAddUpdateRef.allPermissionSelected = false
      return
    }
    if ((item as any).children) {
      let children = (item as any).children || []
      for (let child of children) {
        if (!child.selected) {
          roleAddUpdateRef.allPermissionSelected = false
          return
        }
      }
    }
  }

  roleAddUpdateRef.allPermissionSelected = true
}

onMounted(() => {
  getDataList()
  startGetPermissionTree()
})
</script>
<style lang="scss" scoped>
.role-page {
  background-color: #fff;
  padding: 20px;
  max-height: calc(100vh - 134px);
}

.btns-fun-field {
  margin-bottom: 20px;
}

.pagination-field {
  display: flex;
  justify-content: flex-end;
  margin: 20px 0;
}

.btn-inner {
  display: flex;
  justify-content: center;
  color: #fff;
}
</style>
